const axios = require('axios')
const util = require('util')
const User = require('../models/user')
const { generateToken } = require('../../core/util')
const Auth = require('../../middlewares/auth')
class WXManager {
  static async codeToToKen(code) {
    // code 小程序生成  
    // openid 小程序的唯一标识
    const url = util.format(global.config.wx.loginUrl, global.config.wx.appId, global.config.wx.appSecret, code)
    const result = await axios.get(url)
    if(result.status !=200) {
      throw new global.errs.AuthFailed('openId获取失败')
    }
    if(result.data.errorCode && result.data.errorCode !== 0) {
      throw new global.errs.AuthFailed('openid获取失败'+ result.data.errorCode)
    }
    
    let user = await User.getUserByOpenId(result.data.openid)
    if(!user) {
      user = await User.registerByOpenid(result.data.openid)
    }
    return generateToken(user.id, Auth.USER)
  }
}


module.exports = WXManager